﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;

public partial class mystudy_Study_Left : System.Web.UI.Page
{
    protected DataSet ds_pub;
    protected string forum_id, forum_name, Request_CurrentPage, pub_forum_id;
    protected int emplid_int = 0;
    //声明表格对象
    DataTable dt;
    //声明视图对象
    DataView dv;
    string s_where, s_order, s_select;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["sUserName"] == null)
        {

            Response.Write("<script language=javascript>alert('未登录或登录已到期，请返回登录页面重新登录！');window.parent.close();</script>");
            //Response.Write("<script language=javascript> window.open('../logout.aspx','','fullscreen=yes')</script>");
            return;
        }
        if (!Page.IsPostBack)       //初始状态下，所有控件不可用。通过身份判断，启用相关控件。
        {
            MyDataGrid.Enabled = true;
            BtnNew.Enabled = false;
            BtnNew.Visible = false;
            //BtnAppend.Enabled = false;
            //BtnAppend.Visible = false;
            BtnBaoming.Enabled = false;
            BtnBaoming.Visible = false;
            BtnDefin.Enabled = false;
            BtnDefin.Visible = false;
            DplConfirm.Enabled = false;
            DplConfirm.Visible = false;
            DplPingfen.Enabled = false;
            DplPingfen.Visible = false;

            //--------------------------
            //string s_where = " where f_layer=1 and f_topic like '%" + Session["stopic"].ToString() + "%'";
            //string s_order = " order by f_imp desc,f_date desc";
            //string s_select = "select title_id,f_title,f_writer,f_dep,f_date,f_read,f_reply,f_username1,f_topic,f_imp from bbs ";
            //string sql = s_select + s_where + s_order;
            //setDataView(sql);
            //dv = new DataView(dt);

            //--------------------------

        }
        lblKecheng.Text = Session["skechengname"].ToString();
        string pattern = "[^\x00-\xff]";
        string _pattern = "[\x00-\xff]";
        MatchCollection chinese = Regex.Matches(lblKecheng.Text, pattern, RegexOptions.Multiline);
        MatchCollection notChinese = Regex.Matches(lblKecheng.Text, _pattern, RegexOptions.Multiline);
        string temp = String.Empty;
        foreach (Match match in chinese)
        {
            temp += match.Value;
            temp = temp.Replace(match.Value, "rr");
        }
        foreach (Match match in notChinese)
        {
            temp += match.Value;
        }

        if (temp.Length > 9)
        {
            lblKecheng.Font.Size = new FontUnit(25, UnitType.Pixel);
        }
        if (temp.Length > 11)
        {
            lblKecheng.Font.Size = new FontUnit(22, UnitType.Pixel);
        }
        if (temp.Length > 20)
        {
            lblKecheng.Font.Size = new FontUnit(16, UnitType.Pixel);
        }

        lblLaoshi.Text = Session["slaoshiusername1"].ToString();
        lblJigou.Text = Session["skechengjigou"].ToString();
        bool z1 = (Session["sRole"].ToString() == "学员" | Session["sRole"].ToString() == "老师") & (Session["sKecheng"].ToString().IndexOf("," + Session["sid"].ToString() + ",") >= 0 | Session["sKechenged"].ToString().IndexOf("," + Session["sid"].ToString() + ",") >= 0); //课程在学员或老师的已学或正学/已教正教课程里
        if (Session["sRole"].ToString() == "老师" & Session["slaoshi"].ToString() == Session["sUsername"].ToString())
        {
            z1 = true;
        }
        bool z2 = Session["sRole"].ToString() == "管理员"; //对平台管理员，所有内容均可操作
        bool z3 = Session["sRole"].ToString() == "机构" & Session["sJigou"].ToString() == Session["skechengjigou"].ToString();  //对机构用户，只要课程所属机构是该机构即可操作
        //除了上述4中情况之外，其他人员均视为无效用户

        if (Session["sRole"].ToString() == "学员")
        {
            if (z1) //学员，且已经报名学习
            {
                if (Session["sKecheng_Voted"].ToString().IndexOf("," + Session["sid"] + ",") <= 0)    //还没有评分(本课程代码不在已投票课程序列中）
                {
                    DplPingfen.Enabled = true;
                    DplPingfen.Visible = true;
                    BtnDefin.Enabled = true;
                    BtnDefin.Visible = true;
                }
                //下边代码enable课程目录
                MyDataGrid.Enabled = true;

            }
            else    //学员，还没有报名学习课程，则显示“报名”按钮。//不显示 课程目录
            {
                BtnBaoming.Visible = true;
                BtnBaoming.Enabled = true;
                MyDataGrid.Visible = false;

            }

        }
        if (Session["sRole"].ToString() == "老师")
        {
            if (z1) //老师，且本课程是该老师教授
            {
                //下边代码enable课程目录，且enable“发布”、“回复”按钮
                MyDataGrid.Enabled = true;
                BtnNew.Visible = true;
                BtnNew.Enabled = true;
                //BtnAppend.Visible = true;
                //BtnAppend.Enabled = true;
                BtnDefin.Visible = true;
                BtnDefin.Enabled = true;
                BtnDefin.Text = "提交";
                BtnDefin.Enabled = false;
                if (Session["sconfirm"].ToString() == "审核未通过" | Session["sconfirm"].ToString() == "终审未通过" | Session["sconfirm"].ToString() == "新建")
                {
                    BtnDefin.Enabled = true;
                }
            }
        }
        if (z2)     //如果是平台管理员
        {
            MyDataGrid.Enabled = true;
            BtnNew.Visible = true;
            BtnNew.Enabled = true;
            //BtnAppend.Visible = true;
            //BtnAppend.Enabled = true;
            //以下将投票改为“终审”
            DplConfirm.Visible = true;
            DplConfirm.Enabled = true;
            BtnDefin.Visible = true;
            BtnDefin.Enabled = true;
            BtnDefin.Text = "终审";//如果该课程状态不是审核通过,则终审按钮Enable=false
            //对于平台管理员，如果课程所属机构为“机构”，则等待审核通过后进行终审。
            //如果所属机构为平台，则见到“提交状态”即直接终审。
            BtnDefin.Enabled = false;
            if (Session["sconfirm"].ToString() == "审核通过")
            {
                BtnDefin.Enabled = true;
            }

            if (Session["sconfirm"].ToString() == "提交" && Session["sjigou"].ToString() == "远程教育平台")
            {
                BtnDefin.Enabled = true;
            }
        }
        if (z3)     //如果是机构管理员，且该课程属于该机构
        {
            MyDataGrid.Enabled = true;
            BtnNew.Visible = true;
            BtnNew.Enabled = true;
            //BtnAppend.Visible = true;
            //BtnAppend.Enabled = true;
            //以下将投票改为“审核”
            DplConfirm.Visible = true;
            DplConfirm.Enabled = true;
            BtnDefin.Visible = true;
            BtnDefin.Enabled = true;
            BtnDefin.Text = "审核";//如果该课程状态不是"提交",则审核按钮Enable=false
            if (Session["sconfirm"].ToString() != "提交")
            {
                BtnDefin.Enabled = false;
            }
        }
        Bind();


    }
    protected void BtnDefin_Click(object sender, EventArgs e)
    {
        string zfuckdo = BtnDefin.Text;
        switch (zfuckdo)
        {

            case "评分":
                zxdscore();

                break;
            case "提交":
                zxdconfirm0();
                break;
            case "审核":
                zxdconfirm1();
                break;
            case "终审":
                zxdconfirm2();
                break;
        }

    }
    protected void zxdscore()       //评分,评分之后因为记录Session[Svoted]
    {
        Conn zxdconn = new Conn();
        //Session[vote]+=,skechengid,
        Session["sKecheng_Voted"] = Session["sKecheng_Voted"].ToString().Trim() + "," + Session["sid"].ToString() + ",";
        //帐户.voted+=,skechengid,
        string zsql = "update account set voted='" + Session["sKecheng_Voted"].ToString() + "' where username='" + Session["sUsername"].ToString() + "'";
        string noth = zxdconn.ExeSql(zsql).ToString();
        //投票：insert into pingfen (课程，用户，分数，系统日期)values ()
        string zxtsj = DateTime.Now.ToString();
        zsql = "insert into pingfen(username,kecheng_id,kecheng,pingfen,pfsj) values('" + Session["sUsername"].ToString() + "'," + Session["sid"].ToString() + ",'" + Session["skechengname"].ToString() + "'," + DplPingfen.SelectedValue.ToString().Trim() + ",'" + zxtsj + "')";
        noth = zxdconn.ExeSql(zsql).ToString();
        //Kecheng.jifen+=积分
        zsql = "update kecheng set jifen=jifen+" + DplPingfen.SelectedValue.ToString().Trim() + " where id=" + Session["sid"].ToString();
        noth = zxdconn.ExeSql(zsql).ToString();
        //投票.enable=false
        //最后,还要将本页面刷新
        Response.Write("<script>parent.location.reload(true)</script>");

    }
    protected void zxdconfirm0()    //提交,提交之
    {
        Conn zconn = new Conn();
        //老师能够提交课程的前提,是考试题目至少有3套题，每套题的分数总额都必须是100分。
        string zsql = "select count(name) from tb_TaoTi where lessonid=" + Session["sid"].ToString();
        string ztaotinum = zconn.sqlFirst(zsql);
        //以下检查考试套题
        //if (ztaotinum == "0")
        //{//处理SQL命令时出错
        //    Response.Write("<script language=javascript>alert('抱歉地通知您,系统处理您的要求出错,请速与系统管理员联系.');if(opener!=null){opener.location.reload();window.close();}</script>");
        //    return;
        //}
        //else
        //{
            //if (Int16.Parse(ztaotinum) < 3)
            //{

            //    string msg="<script language=javascript>alert('您的课程无法提交,请至少准备3套试题,以便学员完成学习后进行考核,按任意键返回.');if(opener!=null){opener.location.reload();window.close();}</script>";
            //    ClientScript.RegisterStartupScript(this.GetType(), "msg", msg, false);
            //    return;
            //}

        //}
        //套题检查完毕
        //以下检查每套题总分
        zsql = "select sum(score) from tb_Questions where que_lessonid=" + Session["sid"].ToString() + " group by que_taotiid";
        SqlDataReader reader1 = zconn.Reader(zsql);
        while (reader1.Read())
        {
            int ztotalscore = reader1.GetInt32(0);
            if (ztotalscore != 100)
            {
                string msg="<script language=javascript>alert('每套考题的总分都必须是100分,请调整您的题目分数.');if(opener!=null){opener.location.reload();window.close();}</script>";
                ClientScript.RegisterStartupScript(this.GetType(), "msg", msg, false);
                return;
            }
        }
        reader1.Dispose();
        zconn.Dispose();
        //检查套题总分完毕


        string zfuckdo;
        string zxtsj = DateTime.Now.ToString();
        zfuckdo = "提交";
        Session["sconfirm"] = zfuckdo;
        zsql = "update kecheng set confirm='" + zfuckdo + "',xtsj2='" + zxtsj + "' where id=" + Session["sid"].ToString();
        zconn = new Conn();

        string noth = zconn.ExeSql(zsql).ToString();
        zconn.Dispose();
        //最后,还要将本页面刷新
        Response.Write("<script>parent.location.reload(true)</script>");
    }
    protected void zxdconfirm1()    //审核
    {
        Conn zxdconn = new Conn();
        string zfuckdo;
        string zxtsj = DateTime.Now.ToString();
        if (DplConfirm.SelectedValue.ToString() == "通过")
        {
            zfuckdo = "审核通过";
        }
        else
        {
            zfuckdo = "审核未通过";
        }
        Session["sconfirm"] = zfuckdo;
        string zsql = "update kecheng set confirm='" + zfuckdo + "',xtsj2='" + zxtsj + "' where id=" + Session["sid"].ToString();
        string noth = zxdconn.ExeSql(zsql).ToString();
        zxdconn.Dispose();
        //最后,还要将本页面刷新
        Response.Write("<script>parent.location.reload(true)</script>");

    }
    protected void zxdconfirm2()    //终审
    {
        Conn zxdconn = new Conn();
        string zfuckdo;
        string zstsj = DateTime.Now.ToString();
        if (DplConfirm.SelectedValue.ToString() == "通过")
        {
            zfuckdo = "终审通过";
        }
        else
        {
            zfuckdo = "终审未通过";
        }
        string zxtsj = DateTime.Now.ToString();
        Session["sconfirm"] = zfuckdo;
        string zsql = "update kecheng set confirm='" + zfuckdo + "',xtsj2='" + zxtsj + "' where id=" + Session["sid"].ToString();
        string noth = zxdconn.ExeSql(zsql).ToString();
        zxdconn.Dispose();
        //最后,还要将本页面刷新
        Response.Write("<script>parent.location.reload(true)</script>");
    }
    protected void BtnBaoming_Click(object sender, EventArgs e)
    {
        if ((Session["sKecheng"].ToString().IndexOf("," + Session["sid"].ToString() + ",") >= 0) | (Session["sKechenged"].ToString().IndexOf("," + Session["sid"].ToString() + ",") >= 0))   //尽管我已经作过了约束，报名的学员看不到"报名"按钮,但为了保险还是加入此判断
        {
            
            string msg="<script language=javascript>alert('不用重复报名您已经报名参加了该课程，不用重复报名');if(opener!=null){opener.location.reload();window.close();}</script>";
            ClientScript.RegisterStartupScript(this.GetType(), "msg", msg, false);
        }
        else       //这里才是报名的代码
        {
            Conn zconn = new Conn();
            //首先应该判断：如果学生储值金额小于学费，则提示不能报名
            string zchuzhisql = "select chuzhi from account where username='" + Session["sUsername"].ToString() + "'";
            string zchuzhi = zconn.sqlFirst(zchuzhisql);
            string zxuefeisql = "select xuefei from kecheng where id=" + Session["sid"].ToString();
            string zxuefei1 = zconn.sqlFirst(zxuefeisql);

            if (float.Parse(zchuzhi) < float.Parse(zxuefei1))
            {
                zconn.Dispose();
                Response.Write("<script language=javascript>alert('您的储值金额不足，请充值后再报名。。。。。');if(opener!=null){opener.location.reload();window.close();}</script>");
                return;
            }
            //流程:
            //插入消费记录
            //session[“sKecheng”]+=, kecheng.id,
            //account.kecheng= session[“sKecheng”]。Tostring()
            //Account.已收课费+=已收课费
            //Kecheng.xuesheng=,xuesheng_id,
            //response.redirect(kecheng_play_temp.aspx

            string zxtsj = DateTime.Now.ToString();
            //首先将session变量更新
            Session["sKecheng"] = Session["sKecheng"].ToString() + "," + Session["sid"].ToString() + ",";

            //取得本课程的课程费用
            string zsql = "";
            zsql = "select xuefei from kecheng where id=" + Session["sid"].ToString();
            string zxuefei = zconn.sqlFirst(zsql).ToString().Trim();


            //修改本用户帐户,加入课程代码,
            zsql = "update account set [kecheng]='" + Session["sKecheng"].ToString() + "',[chuzhi]=[chuzhi]-" + zxuefei + ",[yiskf]=[yiskf]+" + zxuefei + " where [username]='" + Session["sUsername"].ToString() + "'";
            zconn.ExeSql(zsql);
            //插入消费记录-用户名称,消费对象,课程名称,消费金额,系统时间.
            //2008-03-03将该学生的ID加入老师的kecheng字段中

            //修改kecheng表,将本学生的id记入kecheng.xuesheng字段中
            //首先取得kecheng.xuesheng的值,加当前学生用户名后再赋值给kecheng.xuesheng,因为nText型字段不支持set [xuesheng]=[xuesheng]+的形式
            zsql = "select xuesheng from kecheng where [id]=" + Session["sid"].ToString();
            string zxueshenginkecheng = zconn.sqlFirst(zsql);
            if (zxueshenginkecheng == "0")
            {
                zxueshenginkecheng = "";
            }
            zxueshenginkecheng = zxueshenginkecheng + "," + Session["sUserName"].ToString() + ",";
            zsql = "update kecheng set [xuesheng]='" + zxueshenginkecheng + "' where [id]=" + Session["sid"].ToString();
            int noth = zconn.ExeSql(zsql);
            //修改完毕.zxd,2008-5-27

            zsql = "select [kecheng] from account where username='" + Session["slaoshi"].ToString() + "'";
            string zxuesheng = zconn.sqlFirst(zsql);
            if (zxuesheng.IndexOf("," + Session["sUsername"].ToString().Trim() + ",") == 0)//首先判断该学生是否在别的课程中选修过该老师的课程,如果没有,把他加入
            {
                zxuesheng += "," + Session["sUserName"].ToString() + ",";
                zsql = "update account set [kecheng]='" + zxuesheng + "' where username='" + Session["slaoshi"].ToString() + "'";
                zconn.ExeSql(zsql);
            }
            //加入完毕
            zsql = "insert into xiaofei (username,topic,topic1,xfje,xfsj) values('" + Session["sUsername"].ToString() + "','课程报名','" + Session["skechengname"].ToString() + "'," + zxuefei + ",'" + zxtsj + "')";
            int nothresult = zconn.ExeSql(zsql);
            zconn.Dispose();
            //最后,还要将本页面刷新
            Response.Write("<script>parent.location.reload(true)</script>");
        }
    }
    protected void BtnNew_Click(object sender, EventArgs e)
    {
    }

    private void Bind()
    {
        Conn conn = new Conn();
        forum_id = Session["stopic"].ToString();
        pub_forum_id = forum_id;
        //Request_CurrentPage = Request.Params["CurrentPage"];
        if (forum_id == null)
            forum_id = conn.s_announce;
        //连接数据库，找到forum_name
        string nameSql = "select bbsname,urlpage,dutylist,c_repost,duty_post,c_post,dep_post,deplist from bbsconfig where bbs_id=" + forum_id;
        //			SqlDataReader readerName=conn.Reader(nameSql);
        SqlConnection MyConnection = new SqlConnection(conn.strProvider);
        SqlCommand myCommand = new SqlCommand(nameSql, MyConnection);
        MyConnection.Open();
        SqlDataReader readerName = myCommand.ExecuteReader();
        //判断一下是否有数据
        //2009-8-4 Lnan修改
        if (readerName.Read())
        {
            int sd = Int32.Parse(Session["dutyno"].ToString());
            string dutypost_str = readerName.GetString(4);//发表级别
            int dutypost_int = 1;
            string c_post_str = readerName.GetString(5);//是否可发表
            string dep_post_str = readerName.GetString(6);//可发表部门
            string deplist_str = readerName.GetString(7);//可阅读部门
            string sdepid = "/" + Session["dep"].ToString() + "/";
            int temp1 = deplist_str.IndexOf(sdepid, 0);
            if (deplist_str == "-")
                temp1 = 1;
            //首先判断dutylist可阅读级别,是一个数字
            string dutylist_str = readerName.GetString(2);
            int dutylist_int = 1;
            //查找人员权限表，判断是否可阅读.优先级最高
            //当人员权限表中没有设置（为空）时，考虑部门和级别是否允许
            //string str_temp = Y_read(emplid_int, Int32.Parse(forum_id));
            //if (str_temp == "0")
            //    Response.Redirect("Error.aspx?Info=dutylist", true);
            //else if (str_temp == "")
            //{
            //    if ((sd < dutylist_int) | (temp1 < 0))
            //        Response.Redirect("Error.aspx?Info=dutylist", true);
            //}
            //-------------------------------------------
            forum_name = readerName.GetString(0);
            Session["Forum_Name"] = forum_name;

            if (readerName.GetString(1) != "-")
            {
                string urlpage = readerName.GetString(1);
                if (forum_name == "考勤管理")
                {
                    string dutyno_t = Session["dutyno"].ToString();
                    string depid_t = Session["depid"].ToString();
                    Response.Redirect(urlpage + "?dutyno=" + dutyno_t + "&username=" + Session["username"].ToString() + "&duty=" + Session["duty"].ToString() + "&email=" + Session["email"].ToString() + "&cid=" + Session["cid"].ToString() + "&depid=" + depid_t + "&userno=" + Session["userno"].ToString());
                }
                else if ((forum_name == "名片夹") | (forum_name == "会议室") | (forum_name == "查询养老保险") | (forum_name == "查询员工养老") | (forum_name == "查询工资") | (forum_name == "查询员工工资") | (forum_name == "修改密码") | (forum_name == "个人信息查询") | (forum_name == "查询电脑配置") | (forum_name == "登记日程安排") | (forum_name == "日程安排") | (forum_name == "待办事宜") | (forum_name == "发文") | (forum_name == "历史记录") | (forum_name == "公文管理") | (forum_name == "查看用户信息") | (forum_name == "查看访问记录"))
                {
                    string dutyno_t = Session["dutyno"].ToString();
                    string depid_t = Session["depid"].ToString();
                    Response.Redirect("../app/pub.asp?forum_id=" + forum_id + "&dutyno=" + dutyno_t + "&username=" + Session["username"].ToString() + "&duty=" + Session["duty"].ToString() + "&email=" + Session["email"].ToString() + "&cid=" + Session["cid"].ToString() + "&depid=" + depid_t + "&userno=" + Session["userno"].ToString());
                }
                else if (forum_name == "外部邮件")
                {
                    string s_url = "https://210.72.224.217/exchange/" + Session["username"].ToString();
                    Response.Redirect(s_url, true);
                }
                else
                    Response.Redirect(urlpage);
            }
            else
            {//论坛栏目
                //栏目精华文章和栏目所有文章的sql语句条件不同
                if (Request.Params["elite"] == "1")
                {
                    s_where = " where f_subbbs=0 and f_topic like '%" + forum_id + "%' and f_topic like '%" + conn.s_elite + "%'";
                    //newImg.Visible = false;
                    //LaBack.Visible = true;
                    //LaBack.Text = "[<a href='Content.aspx?forum_id=" + forum_id + "'>返回</a>]";
                }
                else
                {
                    s_where = " where f_subbbs=0 and f_layer=1 and f_topic like '%" + forum_id + "%'";
                    //LaBack.Visible = false;
                }
                s_order = " order by f_imp desc,f_date ";
                s_select = "select title_id,f_title,f_writer,f_dep,f_date,f_read,f_reply,f_username1,f_topic,f_imp from bbs ";
                string sql = s_select + s_where + s_order;

                //初始时、浏览不同的栏目、精华栏目, 需要设置DataView
                //if ((Session["dv_content"] == null) | (LabelTopic.Text != "<b>" + forum_name + "</b>") | (Request.Params["elite"] == "1"))// | (sort_flag=="0"))
                //{
                setDataView(sql);
                //}
                //else
                //{
                //    dt = (DataTable)Session["dv_content"];
                //}
                dv = new DataView(dt);
                if (!IsPostBack)
                {
                    BindGrid();
                }

                //判断是否可回复,0不可回复(公告栏、新闻)，1可回复（论坛），显示的列不同
                string c_repost_str = readerName.GetString(3);
                if (c_repost_str == "0")
                {
                    //eliteImg.Visible = false;
                    //MyDataGrid.Visible = true;
                    //LabelTopic.Text = "<b>" + forum_name + "</b>";
                    //					MyDataGrid.Columns[0].Visible=false;
                    //					MyDataGrid.Columns[1].Visible=false;
                    //					MyDataGrid.Columns[4].Visible=true;
                    //					MyDataGrid.Columns[6].Visible=false;	//最新回复人
                }
                else
                {
                    //eliteImg.Visible = true;
                    //MyDataGrid.Visible = true;
                    //LabelTopic.Text = "<b>" + forum_name + "</b>";
                    //					MyDataGrid.Columns[0].Visible=true;
                    //					MyDataGrid.Columns[1].Visible=true;
                    //					MyDataGrid.Columns[4].Visible=false;
                    //					MyDataGrid.Columns[6].Visible=true;		//最新回复人
                }
            }
        }
        readerName.Close();
        MyConnection.Close();
    }

    public void setDataView(string sql)
    {
        dt = new DataTable();
        //建立数据连接
        Conn conn = new Conn();
        SqlConnection mySqlConnection = new SqlConnection(conn.strProvider);
        SqlCommand mySqlCommand = new SqlCommand("search", mySqlConnection);
        mySqlCommand.CommandType = CommandType.StoredProcedure;
        SqlParameter workParm;
        workParm = mySqlCommand.Parameters.Add("@a_Select", SqlDbType.NVarChar, 500);
        mySqlCommand.Parameters["@a_Select"].Value = sql;
        mySqlConnection.Open();
        //创建SqlDataAdapter对象
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = mySqlCommand;
        //创建DataSet对象
        DataSet ds = new DataSet();
        //将查询结果填充到DataSet对象中
        da.Fill(ds, "dt_content");
        dt = ds.Tables["dt_content"];
        Session["dv_content"] = dt;
        //			dv.Sort = "f_date";
    }


    public void BindGrid()
    {
        //从浏览页（contentview）返回的CurrentPage表示刚刚浏览的页号
        if (Request_CurrentPage != null)
        {
            MyDataGrid.CurrentPageIndex = Int32.Parse(Request_CurrentPage.ToString());
        }
        MyDataGrid.DataSource = dv;
        MyDataGrid.DataBind();

        //Label9.Text = "第" + (MyDataGrid.CurrentPageIndex + 1).ToString() + "页|共" + MyDataGrid.PageCount.ToString() + "页|" + dv.Count.ToString() + "条信息";
        //Label10.Text = "第" + (MyDataGrid.CurrentPageIndex + 1).ToString() + "页|共" + MyDataGrid.PageCount.ToString() + "页|" + dv.Count.ToString() + "条信息";
        //Session["CPage"] = MyDataGrid.CurrentPageIndex.ToString();
        //-------每次DataGrid载入数据时，需要设置单元格中的属性
        //判断是否可见匿名作者的姓名，超级用户dutyno＝99
        Conn conn = new Conn();
        string dutyno_str = Session["dutyno"].ToString();
        for (int i = 0; i < MyDataGrid.Items.Count; i++)
        {
            Label Label6 = (Label)MyDataGrid.Items[i].FindControl("Label6");			//
            Label LaName1 = (Label)MyDataGrid.Items[i].FindControl("LaName1");		//
            Label replyFlag = (Label)MyDataGrid.Items[i].FindControl("replyFlag");	//有当天回复的标识
            Label titleid = (Label)MyDataGrid.Items[i].FindControl("titleid");		//主贴id
            Label Label5 = (Label)MyDataGrid.Items[i].FindControl("Label5");			//回复数
            Label LaReMan = (Label)MyDataGrid.Items[i].FindControl("LaReMan");		//最新回复
            Label Label7 = (Label)MyDataGrid.Items[i].FindControl("Label7");			//日期
            //设置日期的格式 年-月-日 时:分，并且把长度统一
            //string s_date = Label7.Text;
            //int i_date = s_date.LastIndexOf(":");
            //s_date = s_date.Substring(0, i_date);
            //string s_date1 = s_date.Substring(0, 5);
            //string s_date2 = s_date.Substring(5);
            //s_date2 = conn.convert_datetime(s_date2);
            //Label7.Text = s_date1 + s_date2;

            //回复数是否>0，如果大于0再查找是否有回复。
            if ((Label5.Text != "0") & (Label5.Text != ""))
            {
                //查找数据库当前titleid的回复文章是否有当天的记录
                string tid = titleid.Text;
                string s_tid_count = "select count(*) from bbs where f_pos='" + tid + "' and year(f_date)=year(getdate()) and month(f_date)=month(getdate()) and day(f_date)=day(getdate())";
                int si = conn.sqlCount(s_tid_count);

                //展开格式不用今天回复标志
                //					if (si!=0)
                //						replyFlag.Visible=true;

                //对于有回复的帖子，显示最新回复的人的姓名
                string s_reman_sql = "select f_writer,f_username1,f_date from bbs where f_pos='" + tid + "' and f_date=(select max(f_date) from bbs where f_pos='" + tid + "')";
                SqlConnection mySqlConnection = new SqlConnection(conn.strProvider);
                SqlCommand mySqlCommand = new SqlCommand("search", mySqlConnection);
                mySqlCommand.CommandType = CommandType.StoredProcedure;
                SqlParameter workParm;
                workParm = mySqlCommand.Parameters.Add("@a_Select", SqlDbType.NVarChar, 500);
                mySqlCommand.Parameters["@a_Select"].Value = s_reman_sql;
                mySqlConnection.Open();

                SqlDataReader dr = mySqlCommand.ExecuteReader();
                while (dr.Read())
                {
                    string s1 = dr.GetValue(0).ToString();
                    string s2 = dr.GetValue(1).ToString();
                    string s3 = dr.GetValue(2).ToString();
                    s3 = Convert.ToDateTime(s3).ToString("yyyy'-'MM'-'d hh':'mm':'ss");
                    s3 = s3.Substring(0, s3.LastIndexOf(":")); //去掉时间中的秒
                    s3 = s3.Substring(s3.IndexOf("-") + 1);		//去掉时间中的年份
                    s3 = conn.convert_datetime(s3);			//将时间的长度统一
                    int i_name = s1.Length;		//s1是作者名，将两个字的名字转换成三个字。
                    while (i_name < 3)
                    {
                        s1 = s1.Substring(0, 1) + "&nbsp;&nbsp;&nbsp;&nbsp;" + s1.Substring(1, 1);
                        i_name = i_name + 1;
                    }
                    if ((dutyno_str == "99") & (dr.GetValue(0).ToString() == "匿名"))
                        LaReMan.Text = s1 + "." + s2 + "&nbsp;&nbsp;<font color='navy'>|</font>&nbsp;&nbsp;" + s3;
                    else
                        LaReMan.Text = s1 + "&nbsp;&nbsp;<font color='navy'>|</font>&nbsp;&nbsp;" + s3;
                }
            }
            //判断是否可见匿名作者的姓名，dutyno＝99( )
            //if ((dutyno_str == "99") & (Label6.Text == "匿名"))
            //{
            //    LaName1.Visible = true;
            //    LaName1.Text = "." + LaName1.Text + "";
            //}
            //else
            //{
            //    LaName1.Text = "";
            //    LaName1.Visible = false;
            //}
            //精华、新闻有“精”“NEWS”标志
            Label topicLa = (Label)MyDataGrid.Items[i].FindControl("topicLa");
            Label eliteLa = (Label)MyDataGrid.Items[i].FindControl("eliteLa");
            Label newsLa = (Label)MyDataGrid.Items[i].FindControl("newsLa");
            string s_topic = topicLa.Text;
            if (s_topic.IndexOf(conn.s_elite) >= 0)
                eliteLa.Visible = true;
            if (s_topic.IndexOf(conn.s_news) >= 0)
                newsLa.Visible = true;
            //依据重要性：99红加重闪烁；9红加重；8加重；impLa/titleLa
            Label impLa = (Label)MyDataGrid.Items[i].FindControl("impLa");
            Label titleLa = (Label)MyDataGrid.Items[i].FindControl("titleLa");
            string s_impLa = impLa.Text;
            if (s_impLa == "99")
                titleLa.Text = "<SPAN class=navPoint><b><marquee behavior=alternate  style='cursor:hand' onmousemove=\"this.style.color='navy'\" onmouseout=\"this.style.color='red'\">" + titleLa.Text + "</marquee></b></SPAN>";
            else if (s_impLa.Substring(s_impLa.Length - 1, 1) == "9")
                titleLa.Text = "<font color=red><b>" + titleLa.Text + "</b></font>";
            else if (s_impLa.Substring(s_impLa.Length - 1, 1) == "8")
                titleLa.Text = "<b>" + titleLa.Text + "</b>";

            ImageButton ImgOpen = (ImageButton)MyDataGrid.Items[i].FindControl("ImgOpen");
            //回复数是否>0，如果大于0,再显示子贴标题。
            if ((Label5.Text != "0") & (Label5.Text != ""))
            {
                ImgOpen.CommandName = i.ToString();
            }
            else
            {
                ImgOpen.ImageUrl = "Close.gif";
                ImgOpen.Enabled = false;
                ImgOpen.Visible = false;
            }
            this.treelist(i);
        }
        bool z1 = (Session["sRole"].ToString() == "学员" | Session["sRole"].ToString() == "老师") & (Session["sKecheng"].ToString().IndexOf("," + Session["sid"].ToString() + ",") >= 0 | Session["sKechenged"].ToString().IndexOf("," + Session["sid"].ToString() + ",") >= 0); //课程在学员或老师的已学或正学/已教正教课程里
        if (Session["sRole"].ToString() == "老师" & Session["slaoshi"].ToString() == Session["sUsername"].ToString())
        {
            z1 = true;
        }
        bool z2 = Session["sRole"].ToString() == "管理员"; //对平台管理员，所有内容均可操作
        bool z3 = Session["sRole"].ToString() == "机构" & Session["sJigou"].ToString() == Session["skechengjigou"].ToString();  //对机构用户，只要课程所属机构是该机构即可操作
        if (Session["sRole"].ToString() == "老师")
        {
            if (z1) //老师，且本课程是该老师教授
            {
                for (int i = 0; i < MyDataGrid.Items.Count; i++)
                {
                    Label lblManager = (Label)MyDataGrid.Items[i].FindControl("lblManager");
                    lblManager.Visible = true;
                }
            }
        }
        if (z2)     //如果是平台管理员
        {
            for (int i = 0; i < MyDataGrid.Items.Count; i++)
            {
                Label lblManager = (Label)MyDataGrid.Items[i].FindControl("lblManager");
                lblManager.Visible = true;
            }
        }
        if (z3)     //如果是机构管理员，且该课程属于该机构
        {
            for (int i = 0; i < MyDataGrid.Items.Count; i++)
            {
                Label lblManager = (Label)MyDataGrid.Items[i].FindControl("lblManager");
                lblManager.Visible = true;
            }
        }
    }


    protected string convert_datetime(string s)
    {
        int i = s.IndexOf(" ");
        string s1 = s.Substring(0, i);
        string s2 = s.Substring(i + 1);
        int i1 = s1.IndexOf("-");
        int i2 = s2.IndexOf(":");
        string s11 = s1.Substring(0, i1);
        string s12 = s1.Substring(i1 + 1);
        string s21 = s2.Substring(0, i2);
        string s22 = s2.Substring(i2 + 1);
        if (s11.Length < 2)
            s11 = "0" + s11;
        if (s12.Length < 2)
            s12 = "0" + s12;
        if (s21.Length < 2)
            s21 = "0" + s21;
        if (s22.Length < 2)
            s22 = "0" + s22;
        return s11 + "-" + s12 + " " + s21 + ":" + s22;
    }


    public void ImageButton_Command(object sender, CommandEventArgs e)
    {
        Label Id = (Label)MyDataGrid.Items[Int32.Parse(e.CommandName)].FindControl("titleid");
        DataList dlcdList = (DataList)MyDataGrid.Items[Int32.Parse(e.CommandName)].FindControl("dlcdList");
        ImageButton ImgOpen = (ImageButton)MyDataGrid.Items[Int32.Parse(e.CommandName)].FindControl("ImgOpen");
        if (ImgOpen.ImageUrl == "Open.gif")
        {
            ImgOpen.ImageUrl = "Close.gif";
            dlcdList.Visible = true;
            Conn conn = new Conn();
            string Sql = "select f_title,title_id,f_writer,f_date1,f_layer,f_read,f_reply,f_username1 from bbs where f_pos=" + Int32.Parse(Id.Text) + " order by title_id";
            dlcdList.DataSource = conn.Conn_Send(Sql);
            dlcdList.DataBind();
            for (int i = 0; i < dlcdList.Items.Count; i++)
            {
                Label Child = (Label)dlcdList.Items[i].FindControl("Child");
                Label cId = (Label)dlcdList.Items[i].FindControl("cId");
                Label cTitle = (Label)dlcdList.Items[i].FindControl("cTitle");
                Label cUsers = (Label)dlcdList.Items[i].FindControl("cUsers");
                Label cDate = (Label)dlcdList.Items[i].FindControl("cDate");
                Label cLayer = (Label)dlcdList.Items[i].FindControl("cLayer"); //层数
                Label cRead = (Label)dlcdList.Items[i].FindControl("cRead"); //阅读数
                Label cReply = (Label)dlcdList.Items[i].FindControl("cReply"); //回复数
                Label cUsername1 = (Label)dlcdList.Items[i].FindControl("cUsername1"); //姓名
                int layer = Int32.Parse(cLayer.Text);
                string str = "";
                for (int j = 0; j < layer; j++)
                {
                    str = str + "&nbsp;&nbsp;";
                }
                //转换时间格式
                cDate.Text = Convert.ToDateTime(cDate.Text).ToString("yyyy'-'MM'-'d hh':'mm':'ss");
                int i_date = cDate.Text.LastIndexOf(":");
                string s_date = cDate.Text.Substring(0, i_date);
                string s_date1 = s_date.Substring(0, 5);
                string s_date2 = s_date.Substring(5);
                s_date2 = conn.convert_datetime(s_date2);

                //判断作者为匿名时，超级用户可以看到姓名
                string dutyno_str = Session["dutyno"].ToString();
                if ((dutyno_str == "99") & (cUsers.Text == "匿名"))
                {
                    cUsers.Text = cUsers.Text + "." + cUsername1.Text;
                }

                Child.Text = str + "<a class='zhongwen1' target='rbottom' href='../kecheng_mp/uploadimage/mulu_view.aspx?mode=1&title_id=" + Id.Text + "&thistitle=" + cId.Text + "&forum_id=" + Session["stopic"].ToString() + "&#post" + cId.Text + "'>" + cTitle.Text + "</a>" + "&nbsp;&nbsp;<font class=zhongwen1>" + cUsers.Text + "&nbsp;" + s_date1 + s_date2 + "</font>";
            }
        }
        else
        {
            ImgOpen.ImageUrl = "Open.gif";
            dlcdList.Visible = false;
        }
    }

    public void treelist(int k)
    {
        Label Id = (Label)MyDataGrid.Items[k].FindControl("titleid");
        DataList dlcdList = (DataList)MyDataGrid.Items[k].FindControl("dlcdList");
        ImageButton ImgOpen = (ImageButton)MyDataGrid.Items[k].FindControl("ImgOpen");
        if (ImgOpen.ImageUrl == "Open.gif")
        {
            ImgOpen.ImageUrl = "Close.gif";
            dlcdList.Visible = true;
            Conn conn = new Conn();
            string Sql = "select f_title,title_id,f_writer,f_date1,f_layer,f_read,f_reply,f_username1 from bbs where f_pos=" + Int32.Parse(Id.Text) + " order by title_id";
            dlcdList.DataSource = conn.Conn_Send(Sql);
            dlcdList.DataBind();
            for (int i = 0; i < dlcdList.Items.Count; i++)
            {
                Label Child = (Label)dlcdList.Items[i].FindControl("Child");
                Label cId = (Label)dlcdList.Items[i].FindControl("cId");
                Label cTitle = (Label)dlcdList.Items[i].FindControl("cTitle");
                Label cUsers = (Label)dlcdList.Items[i].FindControl("cUsers");
                Label cDate = (Label)dlcdList.Items[i].FindControl("cDate");
                Label cLayer = (Label)dlcdList.Items[i].FindControl("cLayer"); //层数
                Label cRead = (Label)dlcdList.Items[i].FindControl("cRead"); //阅读数
                Label cReply = (Label)dlcdList.Items[i].FindControl("cReply"); //回复数
                Label cUsername1 = (Label)dlcdList.Items[i].FindControl("cUsername1"); //姓名
                int layer = Int32.Parse(cLayer.Text);
                string str = "";
                for (int j = 0; j < layer; j++)
                {
                    str = str + "&nbsp;&nbsp;";
                }
                //转换时间格式
                //int i_date = cDate.Text.LastIndexOf(":");
                //string s_date = cDate.Text.Substring(0, i_date);
                //string s_date1 = s_date.Substring(0, 5);
                //string s_date2 = s_date.Substring(5);
                //s_date2 = conn.convert_datetime(s_date2);

                //判断作者为匿名时，超级用户可以看到姓名
                string dutyno_str = Session["dutyno"].ToString();
                if ((dutyno_str == "99") & (cUsers.Text == "匿名"))
                {
                    cUsers.Text = cUsers.Text + "." + cUsername1.Text;
                }

                Child.Text = str + "<a class='zhongwen1' target='rbottom' href='../kecheng_mp/uploadimage/mulu_view.aspx?mode=1&title_id=" + Id.Text + "&thistitle=" + cId.Text + "&forum_id=" + forum_id.ToString() + "&#post" + cId.Text + "'>" + cTitle.Text + "</a>" + "&nbsp;&nbsp;<font class=zhongwen1>" + "&nbsp;" + "</font>";
            }
        }
        else
        {
            ImgOpen.ImageUrl = "Open.gif";
            dlcdList.Visible = false;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        //Session.Remove("sid");
        //        ②课程对应的论坛序号（topic）Session[“stopic”]
        //③课程所属机构jigou Session[“skechengjigou”]
        //④任课老师laoshi Session[“slaoshi”]  这里是用户名，不是姓名。
        //⑤任课老师姓名：Session[“slaoshiusername1”]
        //⑥课程名称Session[“skechengname”]
        //⑦课程简介Session[“skechengjianjie”]
        //⑧老师简介Session[“slaoshijianjie”]
        //⑨学员已阅读过的章节Session["schapter"]
        //⑩课程的审核标志Session["sconfirm"],

        //Session.Remove("sconfirm");
        //Session.Remove("stopic");
        //Session.Remove("skechengjigou");
        //Session.Remove("slaoshi");
        //Session.Remove("slaoshiusername1");
        //Session.Remove("skechengname");
        //Session.Remove("skechengjianjie");
        //Session.Remove("slaoshijianjie");
        //Session.Remove("schapte");

        //Response.Write("<script>window.close()</script>");
        Response.Write("<script>window.parent.close()</script>");

    }
}
